package net.raebiger.spreadsheetcat.preference;

import net.raebiger.spreadsheetcat.R;
import android.accounts.Account;
import android.content.SharedPreferences;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.util.Log;

import com.google.api.client.googleapis.extensions.android.accounts.GoogleAccountManager;

public class AccountPreferences {
	private final PreferenceActivity context;

	protected static final String PREF_USERNAME = "prefUsername";

	protected AccountPreferences(PreferenceActivity context) {
		this.context = context;
	}

	@SuppressWarnings("deprecation")
	protected void fillGoogleAccounts() {
		GoogleAccountManager googleAccountManager = new GoogleAccountManager(context);
		Account[] accounts = googleAccountManager.getAccounts();
		String[] accountNames = new String[accounts.length];

		for (int i = 0; i < accounts.length; ++i) {
			accountNames[i] = accounts[i].name;
		}
		final ListPreference accountPref = (ListPreference) context.findPreference(PREF_USERNAME);
		accountPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

			@Override
			public boolean onPreferenceChange(Preference preference, Object newValue) {
				updatePrefUserNameSummary(accountPref, newValue.toString());
				return true;
			}
		});

		accountPref.setEntries(accountNames);
		accountPref.setEntryValues(accountNames);
		String storedAccountname = getStoredGoogleAccountnameOrNull();
		updatePrefUserNameSummary(accountPref, storedAccountname);
	}

	protected Account getStoredGoogleAccountOrNull() {
		final String userName = getStoredGoogleAccountnameOrNull();
		if (userName != null) {
			GoogleAccountManager googleAccountManager = new GoogleAccountManager(context);
			Account[] accounts = googleAccountManager.getAccounts();
			for (Account account : accounts) {
				Log.d("SSC", account.name);
				if (userName.equals(account.name)) {
					return account;
				}
			}
		}
		return null;
	}

	protected String getStoredGoogleAccountnameOrNull() {
		SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
		String storedAccountname = sharedPrefs.getString(PREF_USERNAME, null);
		return storedAccountname;
	}

	protected void updatePrefUserNameSummary(ListPreference lpPref, String userNameToShow) {
		if (userNameToShow != null) {
			lpPref.setSummary(String.format(context.getString(R.string.pref_user_name_summary), userNameToShow));
		} else {
			lpPref.setSummary(R.string.pref_user_name_summaryNoneSelected);
		}
	}
}
